﻿namespace ChinaUnicom.Tasks
{
    using System;
    using System.Net;
    using ChinaUnicom.Schedule;

    internal class LoginTask : ITask
    {
        public string Message { get; private set; }

        string mobile; string password; string code;

        public LoginTask(string mobile, string password, string code)
        {
            Message = string.Empty;
            this.mobile = mobile;
            this.password = password;
            this.code = code;
        }

        public void Start()
        {
            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.Login(mobile, password, code, s =>
            {
                if (AfterLogin != null)
                {
                    AfterLogin(this, EventArgs.Empty);
                }

                if (s.StatusCode == HttpStatusCode.OK)
                {
                    Authentication.Current.Signed = s.Result.Contains(mobile);
                    if (!Authentication.Current.Signed)
                    {
                        // 登录失败！
                        Message = Factory.Parser.Failed(s.Result);
                        RaiseFailed();
                    }
                    else
                    {
                        if (Completed != null)
                        {
                            Completed(this, EventArgs.Empty);
                        }
                    }
                }
                else if (s.Exception != null)
                {
                    Message = s.Exception.Message;
                    RaiseFailed();
                }
                else
                {
                    Message = Factory.Parser.Failed(s.Result);
                    RaiseFailed();
                }
            });
        }

        public int Pending { get { return 0; } }

        public event EventHandler Started;

        public event EventHandler Completed;

        public event EventHandler Failed;

        public event EventHandler AfterLogin;

        void RaiseFailed()
        {
            if (Failed != null)
            {
                Failed(this, EventArgs.Empty);
            }
        }
    }
}
